<?php
class BooksController extends AppController {
    var $name = 'Books';
    
    function add() {
        if($this->data) {
            $this->Book->create();
            $this->Book->save($this->data);
            $this->Book->save(array('user_id' => $this->Auth->user('id')));
            $this->redirect(array('controller' => 'users', 'action' => 'home'));
        }
    }
    
    function edit($id = null) {
        $this->Book->id = $id;
        if($this->Auth->user('id') == $this->Book->field('user_id')) {
            if (!$this->data) {
                $this->data = $this->Book->read();
            }
            else {
                $this->Book->save($this->data);
                $this->redirect(array('controller' => 'users', 'action' => 'home'));
            }
        }
        else {
            $this->Session->setFlash("You're not the owner of this book.");
            $this->redirect(array('controller' => 'users', 'action' => 'home'));
        }
    }
    
    function delete($id = null) {
        $this->Book->id = $id;
        if($this->Auth->user('id') == $this->Book->field('user_id')) {
            $this->Book->delete($id);
            $this->Session->setFlash("The book has been deleted.");
            $this->redirect(array('controller' => 'users', 'action' => 'home'));
        }
        else {
            $this->Session->setFlash("You're not the owner of this book.");
            $this->redirect(array('controller' => 'users', 'action' => 'home'));
        }
    }
    
    function change_status($id = null) {
        $this->Book->id = $id;
        if($this->Auth->user('id') == $this->Book->field('user_id')) {
            if($this->Book->field('status') == "In Library") {
                $this->Book->save(array('status' => "Being leased"));
            }
            else {
                $this->Book->save(array('status' => "In Library"));
            }
            $this->Session->setFlash("The status of this book has been changed.");
            $this->redirect(array('controller' => 'users', 'action' => 'home'));
        }
        else {
            $this->Session->setFlash("You're not the owner of this book.");
            $this->redirect(array('controller' => 'users', 'action' => 'home'));
        }
        $this->redirect(array('controller' => 'users', 'action' => 'home'));
    }
    
}
?>
